package com.phb.puhuibao.web.controller;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.SortedMap;
import java.util.TreeMap;
import java.util.UUID;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.json.JSONException;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.idp.pub.constants.Constants;
import com.idp.pub.context.AppContext;
import com.idp.pub.entity.Pager;
import com.idp.pub.service.IBaseService;
import com.idp.pub.utils.DESUtils;
import com.idp.pub.utils.RSAUtils;
import com.idp.pub.web.controller.BaseController;
import com.llpay.client.config.PartnerConfig;
import com.llpay.client.config.ServerURLConfig;
import com.llpay.client.conn.HttpRequestSimple;
import com.llpay.client.utils.LLPayUtil;
import com.llpay.client.vo.CashBean;
import com.llpay.client.vo.PayDataBean;
import com.llpay.client.vo.RetBean;
import com.opensymphony.oscache.util.StringUtil;
import com.phb.puhuibao.common.Functions;
import com.phb.puhuibao.common.alipayapi.AlipayConfig;
import com.phb.puhuibao.common.alipayapi.AlipayNotify;
import com.phb.puhuibao.common.alipayapi.RSA;
import com.phb.puhuibao.entity.ItemInvestment;
import com.phb.puhuibao.entity.MobileUser;

import com.phb.puhuibao.entity.ThirdPayAccount;
import com.phb.puhuibao.entity.ThirdPayLog;
import com.phb.puhuibao.entity.UserAccount;
import com.phb.puhuibao.entity.UserCard;

import com.phb.puhuibao.entity.UserLoan;
import com.phb.puhuibao.service.UserAccountService;
import com.yeepay.TZTService;

@Controller
@RequestMapping(value = "/userAccount")
public class UserAccountController extends BaseController<UserAccount, String> {
	private static final Log LOG = LogFactory.getLog(UserAccountController.class);

	@javax.annotation.Resource(name = "userAccountService")
	public void setBaseService(IBaseService<UserAccount, String> baseService) {
		super.setBaseService(baseService);
	}
	@javax.annotation.Resource(name = "mobileUserService")
	private IBaseService<MobileUser, String> mobileUserService;

	@javax.annotation.Resource(name = "appContext")
	private AppContext appContext;

	@javax.annotation.Resource(name = "thirdPayLogService")
	private IBaseService<ThirdPayLog, String> thirdPayLogService;

	@javax.annotation.Resource(name = "thirdPayAccountService")
	private IBaseService<ThirdPayAccount, String> thirdPayAccountService;

	@javax.annotation.Resource(name = "userAccountService")
	private UserAccountService userAccountService;

	@javax.annotation.Resource(name = "userAccountService")
	private IBaseService<UserAccount, String> baseUserAccountService;

	@javax.annotation.Resource(name = "userCardService")
	private IBaseService<UserCard, String> baseUserCardService;




	@javax.annotation.Resource(name = "userCardService")
	private IBaseService<UserCard, String> userCardService;
	
	@javax.annotation.Resource(name = "jdbcTemplate")
	private JdbcTemplate jdbcTemplate;

	//-----交易记录-----
	@RequestMapping(value = "query")
	@ResponseBody
	public Map<String, Object> query(@RequestParam int pageno,
			@RequestParam String userId) {
		Map<String, Object> data = new HashMap<String, Object>();
		Pager<UserAccount> pager = new Pager<UserAccount>();
		pager.setReload(true);
		pager.setCurrent(pageno);
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("userId", userId);
		map.put("orderBy", "create_time");
		map.put("order", "desc");
		Pager<UserAccount> p = this.getBaseService().findByPager(pager, map);
		
		data.put("result", p.getData());
		data.put("count", p.getTotal());
		data.put("message", "");
		data.put("status", 1);
		return data;
	}

	//-----提现-----
	@RequestMapping(value = "applicationForWithdrwal")
	@ResponseBody
	public Map<String, Object> applicationForWithdrwal(@RequestParam String userId ,@RequestParam String aliAccount , 
			                                           @RequestParam String aliName , @RequestParam  double  amount ,
			                                           @RequestParam String userNote) {
		Map<String, Object> data = new HashMap<String, Object>();		
		MobileUser user = mobileUserService.getById(userId);
		if (user.getUserMoney()< amount) {
			data.put("message", "用户余额不足！");
			data.put("status", 0);
			return data;
		}

		UserAccount entity = new UserAccount();
		entity.setUserId(user.getUserId());
		entity.setAmount(amount);
		entity.setProcessType(1);
		entity.setUserNote(userNote);
		try {
			entity = userAccountService.processSave(entity);
			
		} catch (Exception e) {
			data.put("message", "提现申请失败！" + e.getMessage());
			data.put("status", 0);
			return data;
		}
		data.put("message", "提现申请成功！");
		data.put("status", 1);
		return data;
	}
	//-----我的余额-----
	/*@RequestMapping(value = "getUserMoney")
	@ResponseBody
	public Map<String, Object> getUserMoney(@RequestParam String userId) {
		Map<String, Object> data = new HashMap<String, Object>();		
		try {
		MobileUser user = mobileUserService.getById(userId);
		if (user.getUserMoney()< amount) {
			data.put("message", "用户余额不足！");
			data.put("status", 0);
			return data;
		}

		UserAccount entity = new UserAccount();
		entity.setUserId(user.getUserId());
		entity.setAmount(amount);
		entity.setProcessType(1);
		entity.setUserNote(userNote);
		
			entity = userAccountService.processSave(entity);
			
		} catch (Exception e) {
			data.put("message", "提现申请失败！" + e.getMessage());
			data.put("status", 0);
			return data;
		}
		data.put("message", "提现申请成功！");
		data.put("status", 1);
		return data;
	}*/
	/*//-----提现-----
	@RequestMapping(value="withdraw")
	@ResponseBody
	public Map<String, Object> withdraw(@RequestParam String phone,
			@RequestParam double amount, @RequestParam String cardTop,
			@RequestParam String cardLast) {
		Map<String, String> params = new HashMap<String, String>();
		String uuid = UUID.randomUUID().toString().replace("-", "");
		params.put("requestid", uuid);
		params.put("identityid", phone);
		params.put("identitytype", "4");
		params.put("card_top", cardTop);
		params.put("card_last", cardLast);
		params.put("amount", String.valueOf((int) (amount * 100)));
		params.put("currency", "156");
		params.put("drawtype", "NATRALDAY_URGENT");
		params.put("userip", appContext.getUserIP());
	

		Map<String, String> result = TZTService.withdraw(params);
		
		String status = StringUtils.trimToEmpty(result.get("status"));
		String error_code = StringUtils.trimToEmpty(result.get("error_code"));
		String error_msg = StringUtils.trimToEmpty(result.get("error_msg"));
		String customError = StringUtils.trimToEmpty(result.get("customError"));

		Map<String, Object> data = new HashMap<String, Object>();
		if (!"".equals(error_code)) {
			data.put("message", error_code + ": " + error_msg);
			data.put("status", 0);
			return data;
		} else if (!"".equals(customError)) {
			data.put("message", customError);
			data.put("status", 0);
			return data;
		}

		if ("SUCCESS".equals(status)) {
			data.put("result", uuid);
			data.put("message", "提现请求成功。");
			data.put("status", 1);
			return data;
		} else {
			data.put("message", "请求提交失败。");
			data.put("status", 0);
			return data;
		}
	}*/

	
	

	@RequestMapping(value = "cancel")
	@ResponseBody
	public Map<String, Object> cancel(@RequestParam int accountId) {
		Map<String, Object> data = new HashMap<String, Object>();
		int count = userAccountService.processDelete(accountId);
		if (count == 0) {
			data.put("message", "取消失败！");
			data.put("status", 0);
		} else {
			data.put("message", "取消成功！");
			data.put("status", 1);
		}
		return data;
	}

	@RequestMapping(params = "method=update", method = RequestMethod.POST)
	@ResponseBody
	public Map<String, Object> update(UserAccount entity) {
		Map<String, Object> results = Constants.MAP();
		if (entity.getProcessType() == 1 && entity.getIsPaid() == 1) {
			// Map<String, Object> params = new HashMap<String, Object>();
			// params.put("mUserId", entity.getmUserId());
			// UserCard card = baseUserCardService.unique(params);
			//
			// Map<String, Object> data = withdraw(card.getBankPhone(),
			// entity.getAmount(), card.getBankAccount().substring(0, 6),
			// card.getBankAccount().substring(card.getBankAccount().length() -
			// 4));
			Map<String, Object> data = withdraw(entity.getUserId(),
					entity.getAmount());
			if ((int) data.get("status") == 1) {
				String orderId = (String) data.get("result");
				UserAccount userAccount = new UserAccount();
				userAccount.setAccountId(entity.getAccountId());
				userAccount.setOrderId(orderId);
				try {
					baseUserAccountService.update(userAccount);
				} catch (Exception e) {
					results.put(Constants.SUCCESS, Constants.FALSE);
					results.put(Constants.MESSAGE, e.getMessage());
					return results;
				}
				entity.setIsPaid(3); // 银行处理中
			} else {
				results.put(Constants.SUCCESS, Constants.FALSE);
				results.put(Constants.MESSAGE, (String) data.get("message"));
				return results;
			}
		}
		try {
			userAccountService.confirm(entity);
			results.put(Constants.SUCCESS, Constants.TRUE);
		} catch (Exception e) {
			results.put(Constants.SUCCESS, Constants.FALSE);
			results.put(Constants.MESSAGE, e.getMessage());
		}
		return results;
	}

	

	@RequestMapping(value = "callback")
	@ResponseBody
	public String callback(@RequestParam String data,
			@RequestParam String encryptkey) {
		Map<String, String> result = TZTService.decryptCallbackData(data,
				encryptkey);
		// String merchantaccount =
		// StringUtils.trimToEmpty(result.get("merchantaccount"));
		String orderid = StringUtils.trimToEmpty(result.get("orderid"));

		Map<String, Object> params = new HashMap<String, Object>();
		params.put("orderId", orderid);
		UserAccount entity = baseUserAccountService.unique(params);
		if (entity != null) {
			return "SUCCESS";
		}

		// String yborderid = StringUtils.trimToEmpty(result.get("yborderid"));
		String amount = StringUtils.trimToEmpty(result.get("amount"));
		String identityid = StringUtils.trimToEmpty(result.get("identityid"));
		// String card_top = StringUtils.trimToEmpty(result.get("card_top"));
		// String card_last = StringUtils.trimToEmpty(result.get("card_last"));
		String status = StringUtils.trimToEmpty(result.get("status"));
		// String bankcode = StringUtils.trimToEmpty(result.get("bankcode"));
		// String bank = StringUtils.trimToEmpty(result.get("bank"));
		// String bankcardtype =
		// StringUtils.trimToEmpty(result.get("bankcardtype"));
		// String sign = StringUtils.trimToEmpty(result.get("sign"));
		String errorcode = StringUtils.trimToEmpty(result.get("errorcode"));
		String errormsg = StringUtils.trimToEmpty(result.get("errormsg"));
		String customError = StringUtils.trimToEmpty(result.get("customError"));

		ThirdPayLog log = new ThirdPayLog();
		// log.setLogId(UUID.randomUUID().toString().replace("-", ""));
		log.setLogId(orderid);
		log.setAction("callback");
		log.setParams(data + encryptkey + JSON.toJSONString(result));
		String error = customError;
		if (!"".equals(errorcode)) {
			error = errorcode + ": " + errormsg;
		}

		int logStatus = 0;
		if ("".equals(error)) {
			logStatus = 1;
		}
		log.setError(error);
		log.setStatus(logStatus);
		thirdPayLogService.save(log);

		if (!"".equals(errorcode)) {
			return errorcode + errormsg;
		} else if (!"".equals(customError)) {
			return customError;
		}

		if ("1".equals(status)) {
			params = new HashMap<String, Object>();
			params.put("mUserTel", identityid);
			MobileUser user = mobileUserService.unique(params);
			entity = new UserAccount();
			entity.setUserId(user.getUserId());
			entity.setAmount(((Double.valueOf(amount) / 100)));
			entity.setProcessType(0);
			entity.setUserNote("YEEPAY");
			entity.setOrderId(orderid);
			try {
				entity = userAccountService.processSave(entity);
				return "SUCCESS";
			} catch (Exception e) {
				LOG.error(e);
				e.printStackTrace();
			}
		}
		return "FAILED";
	}


	/**
	 * 交易明细
	 * 
	 * @param startdate
	 * @param enddate
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "checkAccount")
	@ResponseBody
	public ResponseEntity<byte[]> checkAccount(@RequestParam String startdate,
			@RequestParam String enddate, HttpServletRequest request)
			throws Exception {
		HttpHeaders headers = new HttpHeaders();
		headers.setContentType(MediaType.TEXT_PLAIN);
		headers.setContentDispositionFormData("attachment", "account.txt");
		String sysPath = request.getSession().getServletContext()
				.getResource("/cache").getPath();

		Map<String, String> result = TZTService.getPathOfPayClearData(
				startdate, enddate, sysPath);
		String filePath = StringUtils.trimToEmpty(result.get("filePath"));
		String error_code = StringUtils.trimToEmpty(result.get("error_code"));
		String error = StringUtils.trimToEmpty(result.get("error"));
		String customError = StringUtils.trimToEmpty(result.get("customError"));

		if (!"".equals(error_code)) {
			LOG.error(error_code + ": " + error);
			return new ResponseEntity<byte[]>(
					(error_code + ": " + error).getBytes("utf-8"), headers,
					HttpStatus.OK);
			// throw new Exception(error_code + ": " + error);
		} else if (!"".equals(customError)) {
			LOG.error(customError);
			return new ResponseEntity<byte[]>(customError.getBytes("utf-8"),
					headers, HttpStatus.OK);
			// throw new Exception(customError);
		}

		ByteArrayOutputStream baos = null;
		BufferedReader reader = null;
		try {
			baos = new ByteArrayOutputStream();
			reader = new BufferedReader(new FileReader(filePath));
			String line = null;
			int i = 0;
			double totalFee = 0;
			double totalAmount = 0;
			baos.write("交易时间,客户订单号,交易流水号,金额,手续费,类型".getBytes("utf-8"));
			baos.write(System.getProperty("line.separator").getBytes("utf-8"));
			while ((line = reader.readLine()) != null) {
				String[] ls = line.split(",");
				if (ls.length == 14 && "phb".equals(ls[12])) {
					line = ls[3] + "," + ls[4] + "," + ls[5] + "," + ls[7]
							+ "," + ls[9] + ",充值";
					baos.write(line.getBytes("utf-8"));
					baos.write(System.getProperty("line.separator").getBytes(
							"utf-8"));
					i++;
					double amount = Double.valueOf(ls[7]);
					totalAmount += amount;
					double fee = Double.valueOf(ls[9]);
					totalFee += fee;
					ThirdPayAccount entity = thirdPayAccountService
							.getById(ls[5]);
					if (entity == null) {
						entity = new ThirdPayAccount();
						entity.setOrderId(ls[4]);
						entity.setYbOrderId(ls[5]);
						entity.setPayDate(ls[3]);
						entity.setAmount(amount);
						entity.setFee(fee);
						entity.setType("充值");
						thirdPayAccountService.save(entity);
					}
				}
			}
			baos.write(("总交易笔数：" + i).getBytes("utf-8"));
			baos.write(System.getProperty("line.separator").getBytes("utf-8"));
			BigDecimal amountBD = new BigDecimal(totalAmount).setScale(2,
					RoundingMode.DOWN);
			baos.write(("总金额：" + amountBD.doubleValue()).getBytes("utf-8"));
			baos.write(System.getProperty("line.separator").getBytes("utf-8"));
			BigDecimal feeBD = new BigDecimal(totalFee).setScale(2,
					RoundingMode.DOWN);
			baos.write(("总手续费：" + feeBD.doubleValue()).getBytes("utf-8"));
			baos.write(System.getProperty("line.separator").getBytes("utf-8"));
		} finally {
			try {
				if (reader != null) {
					reader.close();
				}
			} catch (IOException ioe) {
				// ignore
			}
		}

		return new ResponseEntity<byte[]>(baos.toByteArray(), headers,
				HttpStatus.OK);
	}

	@RequestMapping(value = "checkAccountRefund")
	@ResponseBody
	public ResponseEntity<byte[]> checkAccountRefund(
			@RequestParam String startdate, @RequestParam String enddate,
			HttpServletRequest request) throws Exception {
		HttpHeaders headers = new HttpHeaders();
		headers.setContentType(MediaType.TEXT_PLAIN);
		headers.setContentDispositionFormData("attachment", "accountRefund.txt");
		String sysPath = request.getSession().getServletContext()
				.getResource("/cache").getPath();

		Map<String, String> result = TZTService.getPathOfRefundClearData(
				startdate, enddate, sysPath);
		String filePath = StringUtils.trimToEmpty(result.get("filePath"));
		String error_code = StringUtils.trimToEmpty(result.get("error_code"));
		String error = StringUtils.trimToEmpty(result.get("error"));
		String customError = StringUtils.trimToEmpty(result.get("customError"));

		if (!"".equals(error_code)) {
			LOG.error(error_code + ": " + error);
			return new ResponseEntity<byte[]>(
					(error_code + ": " + error).getBytes("utf-8"), headers,
					HttpStatus.OK);
			// throw new Exception(error_code + ": " + error);
		} else if (!"".equals(customError)) {
			LOG.error(customError);
			return new ResponseEntity<byte[]>(customError.getBytes("utf-8"),
					headers, HttpStatus.OK);
			// throw new Exception(customError);
		}

		ByteArrayOutputStream baos = null;
		BufferedReader reader = null;
		try {
			baos = new ByteArrayOutputStream();
			reader = new BufferedReader(new FileReader(filePath));
			String line = null;
			int i = 0;
			double totalFee = 0;
			double totalAmount = 0;
			baos.write("交易时间,客户订单号,交易流水号,金额,手续费,类型".getBytes("utf-8"));
			baos.write(System.getProperty("line.separator").getBytes("utf-8"));
			while ((line = reader.readLine()) != null) {
				String[] ls = line.split(",");
				if (ls.length == 15 && "phb".equals(ls[13])) {
					line = ls[3] + "," + ls[4] + "," + ls[5] + "," + ls[8]
							+ "," + ls[10] + ",退款";
					baos.write(line.getBytes("utf-8"));
					baos.write(System.getProperty("line.separator").getBytes(
							"utf-8"));
					i++;
					double amount = Double.valueOf(ls[8]);
					totalAmount += amount;
					double fee = Double.valueOf(ls[10]);
					totalFee += fee;
					ThirdPayAccount entity = thirdPayAccountService
							.getById(ls[5]);
					if (entity == null) {
						entity = new ThirdPayAccount();
						entity.setOrderId(ls[4]);
						entity.setYbOrderId(ls[5]);
						entity.setPayDate(ls[3]);
						entity.setAmount(amount);
						entity.setFee(fee);
						entity.setType("退款");
						thirdPayAccountService.save(entity);
					}
				}
			}
			baos.write(("总交易笔数：" + i).getBytes("utf-8"));
			baos.write(System.getProperty("line.separator").getBytes("utf-8"));
			BigDecimal amountBD = new BigDecimal(totalAmount).setScale(2,
					RoundingMode.DOWN);
			baos.write(("总金额：" + amountBD.doubleValue()).getBytes("utf-8"));
			baos.write(System.getProperty("line.separator").getBytes("utf-8"));
			BigDecimal feeBD = new BigDecimal(totalFee).setScale(2,
					RoundingMode.DOWN);
			baos.write(("总手续费：" + feeBD.doubleValue()).getBytes("utf-8"));
			baos.write(System.getProperty("line.separator").getBytes("utf-8"));
		} finally {
			try {
				if (reader != null) {
					reader.close();
				}
			} catch (IOException ioe) {
				// ignore
			}
		}

		return new ResponseEntity<byte[]>(baos.toByteArray(), headers,
				HttpStatus.OK);
	}

	/**
	 * 充值交易详细
	 * 
	 * @param orderId
	 * @return
	 */
	@RequestMapping(params = "method=queryTransaction", method = RequestMethod.GET)
	@ResponseBody
	public Map<String, String> queryPay(@RequestParam String orderId) {
		Map<String, String> result = TZTService.queryByOrder(orderId, "");
		// String merchantaccount =
		// StringUtils.trimToEmpty(result.get("merchantaccount"));
		// String orderidFromYeepay =
		// StringUtils.trimToEmpty(result.get("orderid"));
		// String yborderidFromYeepay =
		// StringUtils.trimToEmpty(result.get("yborderid"));
		// String amount = StringUtils.trimToEmpty(result.get("amount"));
		// String currency = StringUtils.trimToEmpty(result.get("currency"));
		// String sourcefee = StringUtils.trimToEmpty(result.get("sourcefee"));
		// String targetfee = StringUtils.trimToEmpty(result.get("targetfee"));
		// String sourceamount =
		// StringUtils.trimToEmpty(result.get("sourceamount"));
		// String targetamount =
		// StringUtils.trimToEmpty(result.get("targetamount"));
		// String ordertime = StringUtils.trimToEmpty(result.get("ordertime"));
		// String closetime = StringUtils.trimToEmpty(result.get("closetime"));
		// String type = StringUtils.trimToEmpty(result.get("type"));
		// String status = StringUtils.trimToEmpty(result.get("status"));
		// String refundtotal =
		// StringUtils.trimToEmpty(result.get("refundtotal"));
		// String productcatalog =
		// StringUtils.trimToEmpty(result.get("productcatalog"));
		// String productname =
		// StringUtils.trimToEmpty(result.get("productname"));
		// String productdesc =
		// StringUtils.trimToEmpty(result.get("productdesc"));
		// String bank = StringUtils.trimToEmpty(result.get("bank"));
		// String bankcardtype =
		// StringUtils.trimToEmpty(result.get("bankcardtype"));
		// String bankcode = StringUtils.trimToEmpty(result.get("bankcode"));
		// String sign = StringUtils.trimToEmpty(result.get("sign"));
		String error_code = StringUtils.trimToEmpty(result.get("error_code"));
		String error = StringUtils.trimToEmpty(result.get("error"));
		String customError = StringUtils.trimToEmpty(result.get("customError"));

		Map<String, String> data = new HashMap<String, String>();
		if (!"".equals(error_code)) {
			data.put(Constants.SUCCESS, Constants.FALSE);
			data.put(Constants.MESSAGE, error_code + ": " + error);
			return data;
		} else if (!"".equals(customError)) {
			data.put(Constants.SUCCESS, Constants.FALSE);
			data.put(Constants.MESSAGE, customError);
			return data;
		}

		return result;
	}

	/**
	 * 易宝退款详细
	 * 
	 * @param orderId
	 * @return
	 */
	@RequestMapping(params = "method=queryRefund", method = RequestMethod.GET)
	@ResponseBody
	public Map<String, String> queryRefund(@RequestParam String orderId) {
		Map<String, String> result = TZTService.refundQuery(orderId);
		// String merchantaccount =
		// StringUtils.trimToEmpty(result.get("merchantaccount"));
		// String orderidFromYeepay =
		// StringUtils.trimToEmpty(result.get("orderid"));
		// String yborderid = StringUtils.trimToEmpty(result.get("yborderid"));
		// String origyborderid =
		// StringUtils.trimToEmpty(result.get("origyborderid"));
		// String amount = StringUtils.trimToEmpty(result.get("amount"));
		// String fee = StringUtils.trimToEmpty(result.get("fee"));
		// String currency = StringUtils.trimToEmpty(result.get("currency"));
		// String ordertime = StringUtils.trimToEmpty(result.get("ordertime"));
		// String closetime = StringUtils.trimToEmpty(result.get("closetime"));
		// String status = StringUtils.trimToEmpty(result.get("status"));
		// String cause = StringUtils.trimToEmpty(result.get("cause"));
		// String sign = StringUtils.trimToEmpty(result.get("sign"));
		String error_code = StringUtils.trimToEmpty(result.get("error_code"));
		String error = StringUtils.trimToEmpty(result.get("error"));
		String customError = StringUtils.trimToEmpty(result.get("customError"));

		Map<String, String> data = new HashMap<String, String>();
		if (!"".equals(error_code)) {
			data.put(Constants.SUCCESS, Constants.FALSE);
			data.put(Constants.MESSAGE, error_code + ": " + error);
			return data;
		} else if (!"".equals(customError)) {
			data.put(Constants.SUCCESS, Constants.FALSE);
			data.put(Constants.MESSAGE, customError);
			return data;
		}

		return result;
	}

	/**
	 * 退款
	 * 
	 * @param entity
	 * @return
	 */
	@RequestMapping(params = "method=refund", method = RequestMethod.POST)
	@ResponseBody
	public Map<String, String> refundPay(@RequestParam String orderId) {
		Map<String, String> result = TZTService.queryByOrder(orderId, "");
		// String orderidFromYeepay =
		// StringUtils.trimToEmpty(result.get("orderid"));
		String yborderidFromYeepay = StringUtils.trimToEmpty(result
				.get("yborderid"));
		String amount = StringUtils.trimToEmpty(result.get("amount"));
		String error_code = StringUtils.trimToEmpty(result.get("error_code"));
		String error = StringUtils.trimToEmpty(result.get("error"));
		String customError = StringUtils.trimToEmpty(result.get("customError"));

		Map<String, String> data = new HashMap<String, String>();
		if (!"".equals(error_code)) {
			data.put(Constants.SUCCESS, Constants.FALSE);
			data.put(Constants.MESSAGE, error_code + ": " + error);
			return data;
		} else if (!"".equals(customError)) {
			data.put(Constants.SUCCESS, Constants.FALSE);
			data.put(Constants.MESSAGE, customError);
			return data;
		}

		Map<String, String> params = new HashMap<String, String>();
		params.put("orderid", orderId);
		params.put("origyborderid", yborderidFromYeepay);
		// params.put("amount", (int) (entity.getAmount() * 100) + "");
		params.put("amount", amount);
		params.put("currency", "156");
		params.put("cause", "");

		result = TZTService.refund(params);
		// String merchantaccountFromYeepay =
		// StringUtils.trimToEmpty(result.get("merchantaccount"));
		// String orderidFromYeepay =
		// StringUtils.trimToEmpty(result.get("orderid"));
		// String yborderid = StringUtils.trimToEmpty(result.get("yborderid"));
		// String origyborderidFromYeepay =
		// StringUtils.trimToEmpty(result.get("origyborderid"));
		// String amountFromYeepay =
		// StringUtils.trimToEmpty(result.get("amount"));
		// String fee = StringUtils.trimToEmpty(result.get("fee"));
		// String currencyFromYeepay =
		// StringUtils.trimToEmpty(result.get("currency"));
		// String timestamp = StringUtils.trimToEmpty(result.get("timestamp"));
		// String remain = StringUtils.trimToEmpty(result.get("remain"));
		// String signFromYeepay = StringUtils.trimToEmpty(result.get("sign"));
		error_code = StringUtils.trimToEmpty(result.get("error_code"));
		error = StringUtils.trimToEmpty(result.get("error"));
		customError = StringUtils.trimToEmpty(result.get("customError"));

		if (!"".equals(error_code)) {
			data.put(Constants.SUCCESS, Constants.FALSE);
			data.put(Constants.MESSAGE, error_code + ": " + error);
			if ("100309".equals(error_code)) {
				Map<String, Object> p = new HashMap<String, Object>();
				p.put("orderId", orderId);
				UserAccount entity = this.getBaseService().unique(p);
				if (entity.getIsPaid() == 2) {
					return data;
				}
			} else {
				return data;
			}
		} else if (!"".equals(customError)) {
			data.put(Constants.SUCCESS, Constants.FALSE);
			data.put(Constants.MESSAGE, customError);
			return data;
		}

		try {
			userAccountService.refund(orderId);
			if ("".equals(error_code)) {
				data.put(Constants.SUCCESS, Constants.TRUE);
			}
		} catch (Exception e) {
			data.put(Constants.SUCCESS, Constants.FALSE);
			data.put(Constants.MESSAGE, "请与系统管理员联系！" + e.getMessage());
		}
		return data;
	}

	/**
	 * 添加申请
	 * 
	 * @param entity
	 * @return
	 */
	@RequestMapping(params = "method=adminCreate", method = RequestMethod.PUT)
	@ResponseBody
	protected Map<String, Object> adminCreate(UserAccount entity) {
		Map<String, Object> results = Constants.MAP();
		entity.setIsPaid(1);
		try {
			userAccountService.adminCreate(entity);
			results.put(Constants.SUCCESS, Constants.TRUE);
		} catch (Exception e) {
			results.put(Constants.SUCCESS, Constants.FALSE);
			results.put(Constants.MESSAGE, e.getMessage());
		}
		return results;
	}

	// llpay
	@RequestMapping(value = "notify")
	@ResponseBody
	public void notify(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		resp.setCharacterEncoding("UTF-8");
		RetBean retBean = new RetBean();
		String reqStr = LLPayUtil.readReqStr(req);
		if (LLPayUtil.isnull(reqStr)) {
			retBean.setRet_code("9999");
			retBean.setRet_msg("交易失败");
			resp.getWriter().write(JSON.toJSONString(retBean));
			resp.getWriter().flush();
			return;
		}
		try {
			if (!LLPayUtil.checkSign(reqStr, PartnerConfig.YT_PUB_KEY)) {
				retBean.setRet_code("9999");
				retBean.setRet_msg("交易失败");
				resp.getWriter().write(JSON.toJSONString(retBean));
				resp.getWriter().flush();
				return;
			}
		} catch (Exception e) {
			retBean.setRet_code("9999");
			retBean.setRet_msg("交易失败");
			resp.getWriter().write(JSON.toJSONString(retBean));
			resp.getWriter().flush();
			return;
		}
		retBean.setRet_code("0000");
		retBean.setRet_msg("交易成功");
		resp.getWriter().write(JSON.toJSONString(retBean));
		resp.getWriter().flush();

		ThirdPayLog log = new ThirdPayLog();
		String uuid = UUID.randomUUID().toString().replace("-", "");
		log.setLogId(uuid);
		log.setAction("notify");
		log.setParams(reqStr);
		log.setError("");
		log.setStatus(1);
		thirdPayLogService.save(log);

		PayDataBean payDataBean = JSON.parseObject(reqStr, PayDataBean.class);
		if (!"SUCCESS".equals(payDataBean.getResult_pay())) {
			return;
		}

		String oid_paybill = payDataBean.getOid_paybill();
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("orderId", oid_paybill);
		UserAccount entity = baseUserAccountService.unique(params);
		if (entity != null) {
			return;
		}

		String identityid = payDataBean.getInfo_order();
		String cardno = null;
		if (identityid.indexOf(",") > 0) {
			String[] info_order = identityid.split(",");
			identityid = info_order[0];
			cardno = info_order[1];
		}

		params = new HashMap<String, Object>();
		params.put("mUserTel", identityid);
		MobileUser user = mobileUserService.unique(params);

		if (cardno != null) {
			UserCard card = baseUserCardService.getById(cardno);
			if (card == null) {
				card = new UserCard();
				card.setBankAccount(cardno);
				card.setmUserId(user.getUserId());
				card.setBankPhone("");
				baseUserCardService.save(card);
			} else {
				card = new UserCard();
				card.setBankAccount(cardno);
				card.setmUserId(user.getUserId());
				card.setBankPhone("");
				baseUserCardService.update(card);
			}
		}

		entity = new UserAccount();
		entity.setUserId(user.getUserId());
		String amount = payDataBean.getMoney_order();
		entity.setAmount(((Double.valueOf(amount))));
		entity.setProcessType(0);
		entity.setUserNote("LLPAY");
		entity.setOrderId(oid_paybill);
		try {
			entity = userAccountService.processSave(entity);
		} catch (Exception e) {
			LOG.error(e);
			e.printStackTrace();
		}
	}

	/**
	 * 提现
	 * 
	 * @param muid
	 * @param amount
	 * @return
	 */
	@RequestMapping(value = "withdraw")
	@ResponseBody
	public Map<String, Object> withdraw(@RequestParam int muid,
			@RequestParam double amount) {
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("mUserId", muid);
		UserCard card = baseUserCardService.unique(params);

		CashBean reqBean = new CashBean();
		// reqBean.setUser_id(muid);
		reqBean.setOid_partner(PartnerConfig.OID_PARTNER);
		reqBean.setSign_type(PartnerConfig.SIGN_TYPE);
		String uuid = UUID.randomUUID().toString().replace("-", "");
		reqBean.setNo_order(uuid);
		reqBean.setDt_order(LLPayUtil.getCurrentDateTimeStr());
		reqBean.setMoney_order(amount + "");
		reqBean.setFlag_card("0");
		reqBean.setCard_no(card.getBankAccount());
		MobileUser user = mobileUserService.getById("" + muid);
		reqBean.setAcct_name(user.getUserName());
		reqBean.setInfo_order("提现");
		reqBean.setNotify_url(ServerURLConfig.WITHDRAW_NOTIFY_URL);
		reqBean.setApi_version(PartnerConfig.VERSION);
		reqBean.setPrcptcd(card.getPrcptcd());
		String sign = LLPayUtil.addSign(
				JSON.parseObject(JSON.toJSONString(reqBean)),
				PartnerConfig.TRADER_PRI_KEY);
		reqBean.setSign(sign);
		String reqJson = JSON.toJSONString(reqBean);
		String resJson = HttpRequestSimple.getInstance().postSendHttp(
				ServerURLConfig.WITHDRAW_URL, reqJson);
		RetBean retBean = JSON.parseObject(resJson, RetBean.class);
		Map<String, Object> data = new HashMap<String, Object>();
		data.put("result", uuid);
		data.put("message", retBean.getRet_msg());
		if ("0000".endsWith(retBean.getRet_code())) {
			data.put("status", 1);
		} else {
			data.put("status", 0);
		}
		return data;
	}

	// withdraw notify
	@RequestMapping(value = "withdrawNotify")
	@ResponseBody
	public void withdrawNotify(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		resp.setCharacterEncoding("UTF-8");
		RetBean retBean = new RetBean();
		String reqStr = LLPayUtil.readReqStr(req);
		if (LLPayUtil.isnull(reqStr)) {
			retBean.setRet_code("9999");
			retBean.setRet_msg("交易失败");
			resp.getWriter().write(JSON.toJSONString(retBean));
			resp.getWriter().flush();
			return;
		}
		try {
			if (!LLPayUtil.checkSign(reqStr, PartnerConfig.YT_PUB_KEY)) {
				retBean.setRet_code("9999");
				retBean.setRet_msg("交易失败");
				resp.getWriter().write(JSON.toJSONString(retBean));
				resp.getWriter().flush();
				return;
			}
		} catch (Exception e) {
			retBean.setRet_code("9999");
			retBean.setRet_msg("交易失败");
			resp.getWriter().write(JSON.toJSONString(retBean));
			resp.getWriter().flush();
			return;
		}
		retBean.setRet_code("0000");
		retBean.setRet_msg("交易成功");
		resp.getWriter().write(JSON.toJSONString(retBean));
		resp.getWriter().flush();

		ThirdPayLog log = new ThirdPayLog();
		String uuid = UUID.randomUUID().toString().replace("-", "");
		log.setLogId(uuid);
		log.setAction("withdrawNotify");
		log.setParams(reqStr);
		log.setError("");
		log.setStatus(1);
		thirdPayLogService.save(log);

		JSONObject object = JSON.parseObject(reqStr);
		if (!"SUCCESS".equals(object.getString("result_pay"))) {
			return;
		}

		String no_order = object.getString("no_order");
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("orderId", no_order);
		UserAccount entity = baseUserAccountService.unique(params);
		if (entity.getIsPaid() == 1) {
			return;
		}

		entity.setIsPaid(1);
		userAccountService.confirm(entity);
	}

	/**
	 * 退款
	 * 
	 * @param oid_paybill
	 * @param money_refund
	 * @return
	 */
	@RequestMapping(value = "refund")
	@ResponseBody
	public Map<String, String> refund(@RequestParam String oid_paybill,
			@RequestParam String amount) {
		JSONObject reqObj = new JSONObject();
		reqObj.put("oid_partner", PartnerConfig.OID_PARTNER);
		String uuid = UUID.randomUUID().toString().replace("-", "");
		reqObj.put("no_refund", uuid);
		reqObj.put("dt_refund", LLPayUtil.getCurrentDateTimeStr());
		reqObj.put("money_refund", amount);
		reqObj.put("oid_paybill", oid_paybill);
		reqObj.put("notify_url", ServerURLConfig.REFUND_NOTIFY_URL);
		reqObj.put("sign_type", PartnerConfig.SIGN_TYPE);
		String sign = LLPayUtil.addSign(reqObj, PartnerConfig.TRADER_PRI_KEY);
		reqObj.put("sign", sign);
		String reqJSON = reqObj.toString();
		String resJSON = HttpRequestSimple.getInstance().postSendHttp(
				ServerURLConfig.REFUND_URL, reqJSON);

		Map<String, String> data = new HashMap<String, String>();
		try {
			// 使用 RetBean retBean = JSON.parseObject(resJson,
			// RetBean.class);即可。虽然支付、退款、提现有（同步）返回参数，但由于存在回调的原因，只需考虑返回的2个参数即可
			org.json.JSONObject object = new org.json.JSONObject(resJSON);
			String ret_code = object.getString("ret_code");
			data.put(Constants.MESSAGE, object.getString("ret_msg"));
			if ("0000".endsWith(ret_code)) {
				ThirdPayLog log = new ThirdPayLog();
				log.setLogId(object.getString("oid_refundno")); // phb_muser_account中的order_id保存的是oid_paybill，但oid_paybill无法传到回调
				log.setAction("refund");
				log.setParams(oid_paybill);
				log.setError("");
				log.setStatus(1);
				thirdPayLogService.save(log);
				data.put(Constants.SUCCESS, Constants.TRUE);
			} else {
				data.put(Constants.SUCCESS, Constants.FALSE);
			}
		} catch (JSONException e) {
			data.put(Constants.SUCCESS, Constants.FALSE);
			data.put(Constants.MESSAGE, e.getMessage());
		}
		return data;
	}

	/**
	 * 退款回调
	 * 
	 * @param req
	 * @param resp
	 * @throws ServletException
	 * @throws IOException
	 */
	@RequestMapping(value = "refundNotify")
	@ResponseBody
	public void refundNotify(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		resp.setCharacterEncoding("UTF-8");
		RetBean retBean = new RetBean();
		String reqStr = LLPayUtil.readReqStr(req);
		if (LLPayUtil.isnull(reqStr)) {
			retBean.setRet_code("9999");
			retBean.setRet_msg("交易失败");
			resp.getWriter().write(JSON.toJSONString(retBean));
			resp.getWriter().flush();
			return;
		}
		try {
			if (!LLPayUtil.checkSign(reqStr, PartnerConfig.YT_PUB_KEY)) {
				retBean.setRet_code("9999");
				retBean.setRet_msg("交易失败");
				resp.getWriter().write(JSON.toJSONString(retBean));
				resp.getWriter().flush();
				return;
			}
		} catch (Exception e) {
			retBean.setRet_code("9999");
			retBean.setRet_msg("交易失败");
			resp.getWriter().write(JSON.toJSONString(retBean));
			resp.getWriter().flush();
			return;
		}
		retBean.setRet_code("0000");
		retBean.setRet_msg("交易成功");
		resp.getWriter().write(JSON.toJSONString(retBean));
		resp.getWriter().flush();

		ThirdPayLog log = new ThirdPayLog();
		String uuid = UUID.randomUUID().toString().replace("-", "");
		log.setLogId(uuid);
		log.setAction("refundNotify");
		log.setParams(reqStr);
		log.setError("");
		log.setStatus(1);
		thirdPayLogService.save(log);

		JSONObject object = JSON.parseObject(reqStr);
		String oid_refundno = object.getString("oid_refundno");
		String sta_refund = object.getString("sta_refund");
		if ("2".equals(sta_refund)) { // 退款成功
			log = thirdPayLogService.getById(oid_refundno);
			if (log == null) {
				LOG.error(reqStr);
			} else {
				String oid_paybill = log.getParams();
				Map<String, Object> p = new HashMap<String, Object>();
				p.put("orderId", oid_paybill);
				UserAccount entity = this.getBaseService().unique(p);
				if (entity.getIsPaid() == 2) {
					return;
				}
				userAccountService.refund(oid_paybill);
			}
		}
	}

	/** APP_ID 应用从官方网站申请到的合法appId */
	public static final String WX_APP_ID = "wx28c3e05616e93328";
	/** 商户号 */
	public static final String WX_PARTNER_ID = "1285549801";
	/** 接口链接 */
	public static final String WX_PREPAY_URL = "https://api.mch.weixin.qq.com/pay/unifiedorder";
	/** 商户平台和开发平台约定的API密钥，在商户平台设置 */
	public static final String WX_KEY = "qwertyuiop1234567890asdfghjkl123";

	/**
	 * getWebChatOrder
	 * 
	 * @param id
	 * @return
	 */
	/*@RequestMapping(value = "getWebChatOrder")
	@ResponseBody
	public Map<String, Object> getWebChatOrder(@RequestParam String id,
			HttpServletRequest request) {
		// appid，body，mch_id，nonce_str，notify_url，out_trade_no，total_fee，trade_type，spbill_create_ip，sign
		Map<String, Object> data = new HashMap<String, Object>();
		
		String price;

		
		if (id.startsWith("R-")) {
			String resourceId = id.substring(2);
			resource = resourceService.getById(resourceId);
			price = (int) (resource.getPrice() * resource.getNumber() * 100)
					+ "";
		} else {
 
			String orderId = id.substring(2);
			ResourceOrder order = resourceOrderService.getById(orderId);
			if(order == null){
				data.put("message", "订单不存在");
				data.put("status", 0);
			}
			
			resource = resourceService.getById(order.getResourceId() + "");
			if(resource == null){
				data.put("message", "任务不存在");
				data.put("status", 0);
			}
			if(resource.getTypeId() == 5){//买票
				if (resource.getStatus() == 1) {//竞价
					price = (int) (order.getPrice() * 100) + "";
				}else if (resource.getStatus() == 2) {//付清余款
					//price = (int) ((order.getPrice() - order.getPaiedAmount()) * 100) + "";// 加价后的额度  减去上次付款的额度
					price = (int)(order.getPaiedAmount()*4 + (order.getPrice() - order.getPaiedAmount()))*100 + "";
				}else {// 付款的那一刻 resource状态改变了
					data.put("message", "已卖完！");
					data.put("status", 0);
					return data;
				}
			}else{
				Pager<ResourceOrder> pager = new Pager<ResourceOrder>();
				pager.setCurrent(0);
				Map<String, Object> params = new HashMap<String, Object>();
				params.put("resourceId", resource.getResourceId());
				params.put("status", 1);
				Pager<ResourceOrder> p = resourceOrderService.findByPager(pager,
						params);
				if (p.getTotal() >= resource.getNumber()) {
					data.put("message", "人数已满！");
					data.put("status", 0);
					return data;
				}

				price = (int) (resource.getPrice() * 100) + "";
				
			}
			
			

		}
		price = "1";// 测试用
		String uuid = UUID.randomUUID().toString().replace("-", "");
		String timeStamp = System.currentTimeMillis() / 1000 + "";
		SortedMap<String, String> parameters = new TreeMap<String, String>();
		parameters.put("appid", WX_APP_ID);
		parameters.put("mch_id", WX_PARTNER_ID);
		parameters.put("nonce_str", uuid);
		parameters.put("body", resource.getName());
		SimpleDateFormat dataFormat = new SimpleDateFormat("yyyyMMddHHmmssSSS");
		String timeString = dataFormat.format(new Date());
		parameters.put("out_trade_no", timeString + "-" + id); // 为了重复支付，见关闭订单
		parameters.put("total_fee", price);
		parameters.put("spbill_create_ip", appContext.getUserIP());
		String notifyUrl = request.getScheme() + "://" + appContext.getUserIP()
				+ ":" + request.getServerPort() + request.getContextPath()
				+ "/userAccount/webChatNotifyUrl.shtml";
		parameters.put("notify_url", notifyUrl);
		parameters.put("trade_type", "APP");

		StringBuffer sb = new StringBuffer();
		for (Entry<String, String> entity : parameters.entrySet()) {
			String k = entity.getKey();
			String v = entity.getValue();
			sb.append(k + "=" + v + "&");
		}
		sb.append("key=" + WX_KEY);
		String sign = null;
		try {
			sign = DigestUtils.md5Hex(sb.toString().getBytes("utf-8"));
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		parameters.put("sign", sign);
		String requestXML = Functions.toXml(parameters);
		String returnXML = Functions.httpsRequest(WX_PREPAY_URL, "POST",
				requestXML);
		if(StringUtil.isEmpty(returnXML) ){
			data.put("message", "Functions.httpsRequest return a null string");
			data.put("status", 0);
		}
		Map<String, String> map = Functions.parseXml(returnXML);
		String prepayId = map.get("prepay_id");
		if (!map.get("return_code").equals("SUCCESS")) {
			data.put("message", map.get("return_msg"));
			data.put("status", 0);
		} else if (!map.get("result_code").equals("SUCCESS")) {
			data.put("message", map.get("err_code_des"));
			data.put("status", 0);
		} else if (prepayId == null && !"".equals(prepayId)) {
			data.put("message", "预支付交易失败！");
			data.put("status", 0);
		} else {
			Map<String, String> result = new HashMap<String, String>();
			result.put("appId", WX_APP_ID);
			result.put("nonceStr", uuid);
			result.put("packageValue", "Sign=WXPay");
			result.put("partnerId", WX_PARTNER_ID);
			result.put("prepayId", prepayId);
			result.put("timeStamp", timeStamp);
			String signString = "appid=" + WX_APP_ID + "&noncestr=" + uuid
					+ "&package=Sign=WXPay&partnerid=" + WX_PARTNER_ID
					+ "&prepayid=" + prepayId + "&timestamp=" + timeStamp
					+ "&key=" + WX_KEY;
			sign = null;
			try {
				sign = DigestUtils.md5Hex(signString.getBytes("utf-8"));
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			}
			result.put("sign", sign);
			data.put("result", result);
			data.put("message", "");
			data.put("status", 1);
		}

		return data;
	}

	@RequestMapping(value = "webChatNotifyUrl")
	@ResponseBody
	public void webChatNotifyUrl(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		String returnXML = LLPayUtil.readReqStr(request);
		if (returnXML == null || "".equals(returnXML)) {
			response.getWriter().write("null");
			response.getWriter().flush();
			return;
		}
		Map<String, String> map = Functions.parseXml(returnXML);
		String out_trade_no = map.get("out_trade_no");
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("orderId", out_trade_no);
		UserAccount entity = baseUserAccountService.unique(params);
		if (entity != null) {
			return;
		}

		ThirdPayLog log = new ThirdPayLog();
		log.setLogId(out_trade_no);
		log.setAction("notify_webchat");
		log.setParams(returnXML);
		log.setError("");
		log.setStatus(1);
		thirdPayLogService.save(log);

	 
		
		int muid;
		Resource r = null;
		ResourceOrder o = null;
		// String id;
		if (out_trade_no.indexOf("-R-") > 0) {
			String resourceId = out_trade_no.substring(out_trade_no
					.indexOf("-R-") + 3);
			Resource resource = resourceService.getById(resourceId);
			muid = resource.getmUserId();
			r = new Resource();
			r.setResourceId(resource.getResourceId());
			r.setStatus(1);
			// id = "R-" + resourceId;
		} else {
			String orderId = out_trade_no
					.substring(out_trade_no.indexOf("-O-") + 3);
			ResourceOrder order = resourceOrderService.getById(orderId);
			muid = order.getmUserId();
			o = new ResourceOrder();
			o.setOrderId(order.getOrderId());
			o.setResourceId(order.getResourceId());
			o.setmUserId(order.getmUserId());
			
			
			Resource resource = resourceService.getById(order.getResourceId()+"");
			if(resource.getTypeId()==5){
				
				if(order.getStatus() == 0){//竞价
					o.setPaiedAmount(order.getPrice());// 本次支付额度为order.getPrice()
					o.setStatus(11);
				}else if(order.getStatus() == 12){// 付清余款
					double topayamount = order.getPrice() +  order.getPaiedAmount()*3 ;
					o.setPrice(order.getPaiedAmount() + topayamount);
					o.setPaiedAmount(order.getPaiedAmount() + topayamount);
					o.setStatus(13);
				}
			}else{
				o.setStatus(1);
			}
 
		}

		entity = new UserAccount();
		entity.setmUserId(muid);
		String total_fee = map.get("total_fee");
		entity.setAmount((double) (Integer.valueOf(total_fee)) / 100);
		entity.setProcessType(0);
		entity.setUserNote("WEBCHAT");
		entity.setOrderId(out_trade_no);
		try {
			if (r == null) {
				userAccountService.processSave(entity, o, 33);
			} else {
				userAccountService.processSave(entity, r, 33);
			}
		} catch (Exception e) {
			LOG.error(e);
			e.printStackTrace();
		}

		paySuccess(response);
	}

	private void paySuccess(HttpServletResponse response) {
		SortedMap<String, String> resMap = new TreeMap<String, String>();
		resMap.put("return_code", "SUCCESS");
		resMap.put("return_msg", "OK");

		response.setCharacterEncoding("UTF-8");
		response.setHeader("ContentType", "text/xml");
		response.setHeader("Pragma", "No-cache");
		response.setHeader("Cache-Control", "no-cache");
		response.setDateHeader("Expires", 0);

		PrintWriter writer = null;
		try {
			writer = response.getWriter();
			writer.flush();
			writer.print(Functions.toXml(resMap));
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			writer.close();
		}
	}

	/**
	 * alipay
	 * 
	 * @param id
	 * @return
	 */
	/*@RequestMapping(value = "alipay")
	@ResponseBody
	public Map<String, Object> alipay(@RequestParam String id,
			HttpServletRequest request) {
		Map<String, Object> data = new HashMap<String, Object>();
		Resource resource;
		String price;
		if (id.startsWith("R")) {
			String resourceId = id.substring(2);
			resource = resourceService.getById(resourceId);
			if (resource== null) {
				data.put("message", "资源不存在！");
				data.put("status", 0);
				return data;
			}
			price = resource.getPrice() * resource.getNumber() + "";
		} else {
			String orderId = id.substring(2);
			ResourceOrder order = resourceOrderService.getById(orderId);
			if (order== null) {
				data.put("message", "订单不存在！");
				data.put("status", 0);
				return data;
			}
			resource = resourceService.getById(order.getResourceId() + "");
			 
			if(resource == null){
				data.put("message", "任务不存在");
				data.put("status", 0);
			}
			if(resource.getTypeId() == 5){//买票
				if (resource.getStatus() == 1) {//竞价
					price = (int) (order.getPrice() * 1) + "";
				}else if (resource.getStatus() == 2) {//付清余款
					price = (int)(order.getPaiedAmount()*4 + (order.getPrice() - order.getPaiedAmount())) +"";
				}else{
					data.put("message", "已卖完！");
					data.put("status", 0);
					return data;
				}
			}else{
				Pager<ResourceOrder> pager = new Pager<ResourceOrder>();
				pager.setCurrent(0);
				Map<String, Object> params = new HashMap<String, Object>();
				params.put("resourceId", resource.getResourceId());
				params.put("status", 1);
				Pager<ResourceOrder> p = resourceOrderService.findByPager(pager,
						params);
				if (p.getTotal() >= resource.getNumber()) {
					data.put("message", "人数已满！");
					data.put("status", 0);
					return data;
				}
				price = resource.getPrice() + "";
				
			}
 
			
		}
		price = "0.01";// 测试用 发布的时候要注释掉

		String desc = resource.getResourceDesc();
		if (StringUtils.isEmpty(desc)) {
			desc = resource.getName();
		}
		Map<String, String> params = new HashMap<String, String>();
		params.put("service", AlipayConfig.service);// 接口服务----即时到账
		params.put("partner", AlipayConfig.partner);// 支付宝PID
		params.put("_input_charset", AlipayConfig.input_charset);// 统一编码
		params.put("payment_type", "1");// 支付类型
		String notifyUrl = request.getScheme() + "://" + appContext.getUserIP()
				+ ":" + request.getServerPort() + request.getContextPath()
				+ "/userAccount/alipayNotifyUrl.shtml";
		params.put("notify_url", notifyUrl);// 异步通知页面
		// params.put("seller_email", AlipayConfig.SELLER_EMAIL);//卖家支付宝账号
		params.put("seller_id", AlipayConfig.SELLER_EMAIL);// 卖家支付宝账号
		SimpleDateFormat dataFormat = new SimpleDateFormat("yyyyMMddHHmmssSSS");
		String timeString = dataFormat.format(new Date());
		String out_trade_no = timeString + "-" + id;
		params.put("out_trade_no", out_trade_no); // 为了重复支付，见关闭订单
		params.put("subject", resource.getName());// 商品名称
		params.put("total_fee", price);// 价格
		params.put("body", desc);
		params.put("it_b_pay", "30m");
		params.put("return_url", "m.alipay.com");

		// 订单
		String orderInfo = "partner=\"" + AlipayConfig.partner + "\"";
		orderInfo += "&seller_id=\"" + AlipayConfig.SELLER_EMAIL + "\"";
		orderInfo += "&out_trade_no=\"" + out_trade_no + "\"";
		// 商品名称
		orderInfo += "&subject=\"" + resource.getName() + "\"";
		// 商品详情
		orderInfo += "&body=\"" + desc + "\"";
		orderInfo += "&total_fee=\"" + price + "\"";
		orderInfo += "&notify_url=\"" + notifyUrl + "\"";
		orderInfo += "&service=\"mobile.securitypay.pay\"";
		orderInfo += "&payment_type=\"1\"";
		orderInfo += "&_input_charset=\"utf-8\"";
		orderInfo += "&it_b_pay=\"30m\"";
		// 支付宝处理完请求后，当前页面跳转到商户指定页面的路径，可空
		orderInfo += "&return_url=\"m.alipay.com\"";
		String sign = RSA.sign(orderInfo, AlipayConfig.private_key, "UTF-8");
		try {
			sign = URLEncoder.encode(sign, "UTF-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		params.put("sign", sign);
		params.put("sign_type", "RSA");

		data.put("result", params);
		data.put("message", "");
		data.put("status", 1);
		return data;
	}

	/**
	 * 支付宝回调
	 * 
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 */
	/*@RequestMapping(value = "alipayNotifyUrl")
	@ResponseBody
	public void alipayNotifyUrl(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		String out_trade_no = request.getParameter("out_trade_no");
		if (out_trade_no == null) {
			response.getWriter().write("null");
			response.getWriter().flush();
			return;
		}
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("orderId", out_trade_no);
		UserAccount entity = baseUserAccountService.unique(params);
		if (entity != null) {
			return;
		}

		StringBuffer sb = new StringBuffer();
		Map<String, String[]> requestParams = request.getParameterMap();
		Map<String, String> map = new HashMap<String, String>();
		for (Iterator<String> iter = requestParams.keySet().iterator(); iter
				.hasNext();) {
			String name = iter.next();
			String[] values = requestParams.get(name);
			String valueStr = "";
			for (int i = 0; i < values.length; i++) {
				valueStr = (i == values.length - 1) ? valueStr + values[i]
						: valueStr + values[i] + ",";
			}
			map.put(name, valueStr);
			sb.append(name + ":" + valueStr + ";");
		}
		

		ThirdPayLog log = new ThirdPayLog();
		log.setLogId(out_trade_no);
		log.setAction("notify_alipay");
		log.setParams(sb.toString());
		log.setError("");
		log.setStatus(1);
		thirdPayLogService.save(log);

		int muid;
		Resource r = null;
		ResourceOrder o = null;
		// String id;
		if (out_trade_no.indexOf("-R-") > 0) {
			String resourceId = out_trade_no.substring(out_trade_no
					.indexOf("-R-") + 3);
			Resource resource = resourceService.getById(resourceId);
			muid = resource.getmUserId();
			r = new Resource();
			r.setmUserId(muid);
			r.setResourceId(resource.getResourceId());
			r.setStatus(1);
			// id = "R-" + resourceId;
		} else {
			String orderId = out_trade_no.substring(out_trade_no.indexOf("-O-") + 3);
			ResourceOrder order = resourceOrderService.getById(orderId);
			Resource resource = resourceService.getById(order.getResourceId()+"");
			muid = order.getmUserId();
			o = new ResourceOrder();
			o.setOrderId(order.getOrderId());
			o.setmUserId(muid);
			o.setResourceId(order.getResourceId());
			
			if(resource.getTypeId()==5){//买票
				
				if(order.getStatus() == 0){//竞价
					o.setPaiedAmount(order.getPrice());// 本次支付额度为order.getPrice()
					o.setStatus(11);
				}else if(order.getStatus() == 12){// 付清余款
					double topayamount = order.getPrice() +  order.getPaiedAmount()*3 ;
					o.setPrice(order.getPaiedAmount() + topayamount);
					o.setPaiedAmount(order.getPaiedAmount() + topayamount);
					o.setStatus(13);
				}
				
			}else{
				o.setStatus(1);
			}
			
			// id = "O-" + orderId;
		}

		String trade_status = new String(request.getParameter("trade_status")
				.getBytes("ISO-8859-1"), "UTF-8");
		if (AlipayNotify.verify(map)) { // 验证成功
			entity = new UserAccount();
			entity.setmUserId(muid);
			String total_fee = map.get("total_fee");
			entity.setAmount(Double.valueOf(total_fee));
			entity.setProcessType(0);
			entity.setUserNote("ALIPAY");
			entity.setOrderId(out_trade_no);
			
			
			try {
				if (r == null) {
					userAccountService.processSave(entity, o, 32);
				} else {
					userAccountService.processSave(entity, r, 32);
				}
			} catch (Exception e) {
				LOG.error(e);
				e.printStackTrace();
			}

			if (trade_status.equals("TRADE_FINISHED")) {
			} else if (trade_status.equals("TRADE_SUCCESS")) {
			}
			response.getWriter().write("success");
		} else { // 验证失败
			response.getWriter().write("fail");
		}
		response.getWriter().flush();
	}

	/**
	 * 支付宝退款回调
	 * 
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 */
	/*@RequestMapping(value = "alipayRefundNotifyUrl")
	@ResponseBody
	public void alipayRefundNotifyUrl(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		LOG.error("alipayRefundNotifyUrl");
		String result_details = request.getParameter("result_details");
		if (StringUtils.isEmpty(result_details)) {
			response.getWriter().write("null");
			response.getWriter().flush();
			return;
		}

		LOG.error("alipayRefundNotifyUrl -" + result_details);
		String out_trade_no = result_details.substring(0,
				result_details.indexOf("^"));
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("orderId", out_trade_no);
		params.put("isPaid", 1);
		UserAccount entity = baseUserAccountService.unique(params);
		if (entity != null) {
			return;
		}

		LOG.error("alipayRefundNotifyUrl - ok1");
		StringBuffer sb = new StringBuffer();
		Map<String, String[]> requestParams = request.getParameterMap();
		Map<String, String> map = new HashMap<String, String>();
		for (Iterator<String> iter = requestParams.keySet().iterator(); iter
				.hasNext();) {
			String name = iter.next();
			String[] values = requestParams.get(name);
			String valueStr = "";
			for (int i = 0; i < values.length; i++) {
				valueStr = (i == values.length - 1) ? valueStr + values[i]
						: valueStr + values[i] + ",";
			}
			map.put(name, valueStr);
			sb.append(name + ":" + valueStr + ";");
		}

		String batch_no = request.getParameter("batch_no");
		ThirdPayLog log = new ThirdPayLog();
		log.setLogId(batch_no);
		log.setAction("notify_refund_alipay");
		log.setParams(sb.toString());
		log.setError("");
		log.setStatus(1);
		thirdPayLogService.save(log);

		int muid;
		Resource r = null;
		ResourceOrder o = null;
		// String id;
		if (out_trade_no.indexOf("-R-") > 0) {
			String resourceId = out_trade_no.substring(out_trade_no
					.indexOf("-R-") + 3);
			Resource resource = resourceService.getById(resourceId);
			muid = resource.getmUserId();
			r = new Resource();
			r.setResourceId(resource.getResourceId());
			r.setStatus(1);
			// id = "R-" + resourceId;
		} else {
			String orderId = out_trade_no
					.substring(out_trade_no.indexOf("-O-") + 3);
			ResourceOrder order = resourceOrderService.getById(orderId);
			muid = order.getmUserId();
			o = new ResourceOrder();
			o.setOrderId(order.getOrderId());
			o.setStatus(1);
			// id = "O-" + orderId;
		}

		if (AlipayNotify.verify(map)) { // 验证成功
			entity = new UserAccount();
			entity.setmUserId(muid);
			String total_fee = map.get("total_fee");
			entity.setAmount(Double.valueOf(total_fee));
			entity.setProcessType(1); // 退款
			entity.setUserNote("ALIPAY_REFUND");
			entity.setOrderId(batch_no);
			entity.setIsPaid(1);
			try {
				userAccountService.processRefund(entity, 32);
			} catch (Exception e) {
				LOG.error(e);
				e.printStackTrace();
			}

			response.getWriter().write("success");
		} else { // 验证失败
			response.getWriter().write("fail");
		}
		response.getWriter().flush();
	}*/
}